package wanba.wanbatv.com.wudao.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;
import java.util.HashMap;

import cn.ffcs.itvpay.ItvPayTask;
import wanba.wanbatv.com.wudao.R;
import wanba.wanbatv.com.wudao.api.ApiBuilder;
import wanba.wanbatv.com.wudao.api.ConfigUtils;
import wanba.wanbatv.com.wudao.sqlite.DBManager;
import wanba.wanbatv.com.wudao.sqlite.DatabaseHelper;
import wanba.wanbatv.com.wudao.sqlite.Person;
import wanba.wanbatv.com.wudao.util.Behavior;
import wanba.wanbatv.com.wudao.util.BitmapCache;
import wanba.wanbatv.com.wudao.util.DataReport;
import wanba.wanbatv.com.wudao.util.ProductInfo;
import wanba.wanbatv.com.wudao.util.WanbaMediaPlayer;


/**
 * Created by Forcs on 15/5/15.
 */
public class JiewuChannelActivity extends BaseChannelActivity implements ViewPager.OnPageChangeListener {

    private static final int MAIN_POSITION = 0;

    private ChannelItemAdapter mItemAdapter = null;

    private ChannelItem[] mItems = null;
    private ImageLoader mImageLoader = null;
    private MediaPlayerDelegate mMediaPlayerDelegate = null;
    public String name="街舞";
    public int id = 5;
    private DBManager dbManager;
    static String title=null;
    DatabaseHelper dbHelper=null;
    Drawable bg;
    private WanbaMediaPlayer mMediaPlayer;
    public static ChannelItem mitem=null;
    public static boolean xuanze=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LoginWudaoActivity.LANMU_NUM=7;
        dbHelper = new DatabaseHelper(this);
        dbHelper.addMySportItem(id, name);
        bg = getResources().getDrawable(R.drawable.channel_jw_background);
        setBackground(bg);

        mItemAdapter = new ChannelItemAdapter(this);
        mMediaPlayerDelegate = new MediaPlayerDelegate(this);
        mItemAdapter.setMediaPlayerDelegate(mMediaPlayerDelegate);
        setAdapter(mItemAdapter);
        setOnPageChangeListener(this);
        setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                new OpenwudaoActivityAction(JiewuChannelActivity.this,
                        SimplewudaoPlayerActivity.class, null)
                        .onClick(view);
            }
        });

        RequestQueue rq = Volley.newRequestQueue(this.getApplicationContext());
        String url = new ApiBuilder(ConfigUtils.Channel.CID_CURRENT)
                .withApi(ConfigUtils.Api.CHANNEL_JW)
                .create();
        final JsonObjectRequest request = new JsonObjectRequest(
                url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            JSONArray result = jsonObject.getJSONArray("result");
                            final int n = result.length();
                            mItems = new ChannelItem[n];
                            ProductInfo.Product p = ProductInfo.getInstance().getProductWithId("6");
                            for (int i = 0; i < n; i++) {
                                ChannelItem ci = new ChannelItem();
                                JSONObject item = result.getJSONObject(i);
                                ci.title = item.getString("title");
                                ci.coverUrl = item.getString("icon");
                                ci.videoUrl = item.getString("play_url");
                                ci.tranId = item.getString("tranId");
//                                Log.d("##jiewu",p.code+"");
                                ci.productCode = p.code;
                                ci.contentCode = item.getInt("content_code");
                                ci.cateCode = item.getInt("cate_code");
                                mItems[i] = ci;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        mItemAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                    }
                });
        request.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
        rq.add(request);

        mImageLoader = new ImageLoader(rq, new BitmapCache());
        add();
    }

    /**
     * 构建顶部图片
     *
     * @param contentView 内容
     */
    @Override
    protected void onBuildHeader(ViewGroup contentView) {
        ImageView headerFlag = (ImageView) contentView.findViewById(R.id.channel_header_flag);
        headerFlag.setImageResource(R.drawable.channel_jw_header_flag);
        ImageView headerPortrait = (ImageView) contentView.findViewById(R.id.channel_header_portrait);
        headerPortrait.setImageResource(R.drawable.channel_jw_header_portrait);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (position == MAIN_POSITION) {
            mItemAdapter.setVideoViewVisibility(View.VISIBLE);
            if (!mMediaPlayerDelegate.isPlaying()) {
                mMediaPlayerDelegate.start();
            }
        } else if (mMediaPlayerDelegate.isPlaying()) {
            mMediaPlayerDelegate.stop();
            mItemAdapter.setVideoViewVisibility(View.INVISIBLE);
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        dbHelper.close();
        bg.setCallback(null);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_SETTLING) {

        }
    }

    private static class ChannelItem {
        int id = 0;
        String title = null;
        String coverUrl = null;
        String videoUrl = null;
        String productCode = null;
        String tranId = null;
        int contentCode = 0;
        int cateCode = 0;
    }

    private static class ItemViewHolder {
        TextView txvTitle;
        ImageView imgCover;
        int postion = -1;
    }

    private static class MainViewHolder {
        SurfaceView sfvVideo;
    }

    private class ChannelItemAdapter extends ItemAdapter {

        private Context mContext = null;
        private MediaPlayerDelegate mMpDelegate = null;
        private SurfaceView mSurfaceView = null;

        ChannelItemAdapter(Context context) {
            mContext = context;
        }

        void setMediaPlayerDelegate(MediaPlayerDelegate mediaPlayerDelegate) {
            mMpDelegate = mediaPlayerDelegate;
        }

        @Override
        public int getCount() {
            return mItems != null ? mItems.length : 0;
        }

        @Override
        public ChannelItem getItem(int position) {
            return mItems[position];
        }

        @Override
        public View getMainView(ViewGroup parent, int position, View itemView) {
            MainViewHolder viewHolder = null;
            if (itemView == null) {
                viewHolder = new MainViewHolder();
                itemView = LayoutInflater.from(mContext).inflate(R.layout.channel_main_item_view, null);
                viewHolder.sfvVideo = (SurfaceView) itemView.findViewById(R.id.main_video);
                itemView.setTag(viewHolder);
            } else {
                viewHolder = (MainViewHolder) itemView.getTag();
            }
           final ChannelItem item = getItem(0);
            initVideo(viewHolder.sfvVideo, item.videoUrl, getCurrentItem() == 0);

            mSurfaceView = viewHolder.sfvVideo;
            ((ViewGroup) itemView).getChildAt(0).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Behavior.onEvent(JiewuChannelActivity.this, 3040001, "选择" + item.title);
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("play_url", item.videoUrl);
                    params.put("content_code", item.contentCode + "");
                    params.put("cate_code", item.cateCode + "");
                    params.put("cate_name", "街舞栏目");
                    params.put("title_lanmu", item.title);
                    SharedPreferences sp =JiewuChannelActivity.this.getSharedPreferences("wanba_config",Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("title", item.title);
                    editor.apply();
                    setitem(item);
                    if (mMediaPlayer!=null){
                        try {
                            mMediaPlayer.release();
                            mMediaPlayer=null;
                        }catch (IllegalArgumentException e){
                            e.printStackTrace();
                        }

                    }
                    new OpenwudaoActivityAction(JiewuChannelActivity.this,
                            SimplewudaoPlayerActivity.class, params)
                            .setProductCode(item.productCode)
                            .setTranId(item.tranId)
                            .setNeedAuth(true)
                            .onClick(v);
                }
            });
            return itemView;
        }

        @Override
        public View getItemView(ViewGroup parent, int position, View itemView) {
            ItemViewHolder viewHolder = null;
            if (itemView == null) {
                viewHolder = new ItemViewHolder();
                itemView = LayoutInflater.from(mContext).inflate(R.layout.channel_normal_item_view, null);
                viewHolder.txvTitle = (TextView) itemView.findViewById(R.id.item_title);
                viewHolder.imgCover = (ImageView) itemView.findViewById(R.id.item_cover);
                itemView.setTag(viewHolder);
            } else {
                viewHolder = (ItemViewHolder) itemView.getTag();
            }

            viewHolder.postion = position;

            final ChannelItem item = getItem(position);
            viewHolder.txvTitle.setText(item.title);
            mImageLoader.get(item.coverUrl, ImageLoader.getImageListener(
                    viewHolder.imgCover, R.drawable.logo_gray, R.drawable.logo_gray));

            if (position == 0) {
                ((ViewGroup) itemView).getChildAt(0).requestFocus();
            }
            ((ViewGroup) itemView).getChildAt(0).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Behavior.onEvent(JiewuChannelActivity.this,3040001,"选择"+item.title);
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("play_url", item.videoUrl);
                    params.put("content_code", item.contentCode + "");
                    params.put("cate_code", item.cateCode + "");
                    params.put("cate_name", "街舞栏目");
                    params.put("title_lanmu", item.title);
                    SharedPreferences sp = JiewuChannelActivity.this.getSharedPreferences("wanba_config",Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putString("title", item.title);
                    editor.apply();
                    setitem(item);
                    if (mMediaPlayer!=null){
                        try {
                            mMediaPlayer.release();
                            mMediaPlayer=null;
                        }catch (IllegalArgumentException e){
                            e.printStackTrace();
                        }

                    }
                    new OpenwudaoActivityAction(JiewuChannelActivity.this,
                            SimplewudaoPlayerActivity.class, params)
                            .setProductCode(item.productCode)
                            .setTranId(item.tranId)
                            .setNeedAuth(true)
                            .onClick(v);
                }
            });
            return itemView;
        }

        @Override
        public boolean showMainView() {
            return true;
        }

        private void initVideo(SurfaceView surfaceView, final String url, boolean autoPlay) {
            SurfaceHolder holder = surfaceView.getHolder();
            holder.removeCallback(mMpDelegate);
            mMpDelegate.setAutoPlay(autoPlay);
            mMpDelegate.setUrl(url);
            holder.addCallback(mMpDelegate);

        }

        void setVideoViewVisibility(int visibility) {
            if (mSurfaceView != null) {
                mSurfaceView.setVisibility(visibility);
            }
        }
    }

    private class MediaPlayerDelegate implements SurfaceHolder.Callback {

        private static final int STATE_IDLE = 0;
        private static final int STATE_CREATED = 1;
        private static final int STATE_INITIALIZED = 2;
        private static final int STATE_PREPARED = 3;
        private static final int STATE_PLAYED = 4;

        private Context mContext = null;
        private String mUrl = null;
        private boolean mAutoPlay = true;
        private int mState = STATE_IDLE;

        MediaPlayerDelegate(Context context) {
            mContext = context;
        }

        void setUrl(String url) {
            mUrl = url;
        }

        void setAutoPlay(boolean autoPlay) {
            mAutoPlay = autoPlay;
        }

        boolean isPlaying() {
            return mState == STATE_PLAYED && mMediaPlayer.isPlaying();
        }

        void start() {
            if (mState > STATE_INITIALIZED) {
                mMediaPlayer.start();
                mState = STATE_PLAYED;
            } else if (mState > STATE_CREATED) {
                mMediaPlayer.prepareAsync();
                mMediaPlayer.setVolume(0.5f, 0.5f);
            }
        }

        void stop() {
            if (mState > STATE_INITIALIZED) {
                mMediaPlayer.stop();
                mState = STATE_INITIALIZED;
            }
        }

        void pause() {
            if (mState > STATE_PREPARED) {
                mMediaPlayer.pause();
                mState = STATE_PREPARED;
            }
        }

        void prepare() {
            if (mState > STATE_CREATED) {
                mMediaPlayer.prepareAsync();
                mMediaPlayer.setVolume(0.5f, 0.5f);
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            mMediaPlayer = new WanbaMediaPlayer();
            mState = STATE_CREATED;
            mMediaPlayer.setLooping(true);
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mState = STATE_PREPARED;
                    start();
                }
            });
            try {
                mMediaPlayer.setDisplay(holder);
                mMediaPlayer.setUrl(mUrl, new WanbaMediaPlayer.OnCheckFinishCallback() {
                    @Override
                    public void onCheckFinish(boolean success) {
                        mState = STATE_INITIALIZED;
                        if (mAutoPlay) {
                            prepare();
                        }
                    }
                });

            } catch (IllegalStateException e){
                e.printStackTrace();
            }catch (IOException e) {
                mMediaPlayer.reset();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if (mMediaPlayer!=null){
                try {
                    mMediaPlayer.release();
                    mMediaPlayer = null;
                }catch (IllegalArgumentException e){
                    e.printStackTrace();
                }

            }

            mState = STATE_IDLE;
        }
    }
    public void add(){
        dbManager=new DBManager(this);
        Person person=new Person(1,name);
        dbManager.add(person);
    }
    @Override
    protected void onResume() {
        super.onResume();
        Behavior.onPageResume(this, 208108, "街舞栏目");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Behavior.onPagePause(this, 208108, "街舞栏目");
    }
    public void setitem(ChannelItem item){
        this.mitem=item;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(mitem!=null && xuanze){
            Intent it=new Intent();
            it.setClass(this,SimplewudaoPlayerActivity.class);
            it.putExtra("play_url", mitem.videoUrl);
            it.putExtra("cate_code", mitem.cateCode+"");
            it.putExtra("content_code", mitem.contentCode+"");
            it.putExtra("title",mitem.title);
            it.putExtra("cate_name","街舞栏目");
            mitem=null;
            xuanze=false;
            startActivity(it);
        }
        DataReport.PageRetreat(JiewuChannelActivity.this, "1100", "200021");
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(LoginWudaoActivity.is_dinggou){
            mitem=null;
            xuanze=false;
        }
        DataReport.PageRetreat(JiewuChannelActivity.this, "2100", "200021");
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ItvPayTask.REQUEST_ITYPAY&&resultCode==ItvPayTask.RESULT_ITVPAY) {
            String result = data.getStringExtra("result");
            try {
                JSONObject obj=(JSONObject) new JSONTokener(result).nextValue();
                if(!obj.getString("tradeInfo").equals("") ){
                    LoginWudaoActivity.is_dinggou=true;
                    if(mitem!=null&&xuanze) {
                        if (mMediaPlayer!=null){
                            mMediaPlayer.release();
                            mMediaPlayer=null;
                        }
                        Intent it=new Intent();
                        it.setClass(this,SimplewudaoPlayerActivity.class);
                        it.putExtra("play_url", mitem.videoUrl);
                        it.putExtra("cate_code", mitem.cateCode+"");
                        it.putExtra("content_code", mitem.contentCode+"");
                        it.putExtra("title",mitem.title);
                        it.putExtra("cate_name","街舞栏目");
                        mitem = null;
                        xuanze = false;
                        startActivity(it);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e("huidiao",result);
        }
    }
}
